package droid.frame.utils.android;

import android.annotation.SuppressLint;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.os.SystemClock;

import java.util.HashMap;

import droid.frame.App;

/**
 * 新消息提醒工具类
 *
 * @author coffee<br>
 * 2014年7月17日上午9:25:26
 */
@SuppressLint("UseSparseArrays")
public abstract class SoundPoolExt {
    protected SoundPool soundPool;
    private final int maxStreams = 4;// 最多支持4个流同时播放的
    /**
     * key:raw resource id, value:a sound ID {@link SoundPool#load(Context, int, int)}
     */
    protected HashMap<Integer, Integer> soundMap = new HashMap<Integer, Integer>();

    protected SoundPoolExt() {
        init();
    }

    private void init() {
        soundPool = new SoundPool(maxStreams, AudioManager.STREAM_MUSIC, 100);
        putRawResource();
        // 第一次加载的时候需要延迟50ms(或更多), 否
        // 则如果SoundPool如果还没load完成的话就调用paly会没有声音
        SystemClock.sleep(100);
    }

    protected abstract void putRawResource();

    /**
     * raw文件的资源ID<br>
     * 支持顺序播放多个文件
     *
     * @param maxVolume   是否按照最大音量播放
     * @param soundResIds
     */
    public void play(boolean maxVolume, final Integer... soundResIds) {
        if (soundResIds.length == 0) {
            return;
        }
        if (soundPool == null) {
            init();
        }
        AudioManager mgr = (AudioManager) App.getContext().getSystemService(Context.AUDIO_SERVICE);
        final float streamVolume;
        if (maxVolume) {
            streamVolume = 1.0F;
        } else {
            streamVolume = (float) (mgr.getStreamVolume(AudioManager.STREAM_MUSIC) / mgr.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int soundResId : soundResIds) {
                    Integer soundId = soundMap.get(soundResId);
                    if (soundId == null) {// 如果soundMap中不存在,则加载
                        soundId = soundPool.load(App.getContext(), soundResId, 1);
                    }
                    play(soundId, streamVolume);
                    MediaPlayer mp = MediaPlayer.create(App.getContext(), soundResId);
                    // 音频文件的长度
                    int duration = mp.getDuration();
                    try {
                        Thread.sleep(duration);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    private void play(int soundId, float streamVolume) {
        try {
            // soundPool.setVolume(soundId, 0.0F, streamVolume);
            soundPool.play(soundId, streamVolume, streamVolume, 1, 0, 1f);
        } catch (Exception e) {
            e.printStackTrace();
            Log.w("SoundPoolUtils_", " soundPool.play 异常", e);
        }
    }

}
